package com.seal.yoyoshop.adminweb;

import com.seal.yoyoshop.bin.Admin;
import com.seal.yoyoshop.service.AdminService;
import com.seal.yoyoshop.service.impl.AdminServiceImpl;
import com.seal.yoyoshop.util.SafeUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminResetPassWordServlet", value = "/admin/adminRe")
public class AdminResetPassWordServlet extends HttpServlet {
    private AdminService adminService = new AdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("flag",5);
        request.getRequestDispatcher("/admin/admin_reset.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String idstr = request.getParameter("id");
        Integer id = Integer.parseInt(idstr);
        String password = request.getParameter("password");
        String passwordNew = request.getParameter("passwordNew");

        Admin admin = adminService.getAdminById(id);
        String currentPwd = admin.getPassword();
        String pwd = SafeUtil.encode(password);
        if(currentPwd.equals(pwd)){
            admin.setPassword(SafeUtil.encode(passwordNew));
            boolean isSuccess = adminService.updatePassword(admin);

            HttpSession session = request.getSession();
            session.setAttribute("admin",admin);

            request.setAttribute("msg","修改密码成功");


        }else {
            request.setAttribute("msg","修改密码失败，原密码错误");
        }
        request.setAttribute("flag",5);
        request.getRequestDispatcher("/admin/admin_reset.jsp").forward(request,response);

    }
}
